package name.williamwall.buxoid;
/**
 * This software is made available under the Gnu General Public License v3
 * and has absolutely no waranty. You may change the software to suit your needs.
 * 
 * Author: William Wall, IV
 */

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import android.app.DatePickerDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;

public class Analysis extends ListActivity {
	// menu ids
	private static final int UPDATE_ID = Menu.FIRST;
	private static final int SETTINGS_ID = Menu.FIRST + 1;
	private static final int HELP_ID = Menu.FIRST + 2;
	
	private Button mMonthButton;
	private ImageView mChart;

	private final static String[] MONTH_NAMES = new String [] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
	@Override
	protected void onCreate(Bundle state) {
		super.onCreate(state);
		
		setContentView(R.layout.analysis);
		
		// set button listeners
		Button prev = (Button) findViewById(R.id.view_analysis_prev);
		mMonthButton = (Button) findViewById(R.id.view_analysis_month);
		Button next = (Button) findViewById(R.id.view_analysis_next);
		mChart = (ImageView) findViewById(R.id.view_analysis_chart);
		
		prev.setOnClickListener(new View.OnClickListener () {
			public void onClick(View view) {
				Buxoid.prevMonth();
				fillData();
			}
		});
		
		next.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Buxoid.nextMonth();
				fillData();
			}
		});
		
		mMonthButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				new DatePickerDialog(Analysis.this, mDateSetListener, Buxoid.mYear, Buxoid.mMonth, 1).show();
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		fillData();
	}

	private void fillData() {
//		Log.d("Buxfer", "filling analysis data");
		
		// set title
		setTitle("Buxoid: Expenses");
		
		int month = Buxoid.mMonth;
		int year = Buxoid.mYear;
		
		// set month
		mMonthButton.setText(MONTH_NAMES[month] + " " + year);
		
		// load pie chart
		
		FileInputStream input = null;
		try {
			input = this.openFileInput("analysis"+year+(month+1)+".png");
		} catch (FileNotFoundException e) {
		}
		
		mChart.setImageBitmap(BitmapFactory.decodeStream(input));
		
		String [] from = new String [] {
				BuxoidDb.ANALYSIS_COLOR,
				BuxoidDb.ANALYSIS_TAG,
				BuxoidDb.ANALYSIS_AMOUNT
		};
		
		int [] to = new int [] {
				R.id.row_analysis_color,
				R.id.row_analysis_tag,
				R.id.row_analysis_amount
		};
		
		Cursor c = Buxoid.mDb.fetchAnalysisLegend(month + 1, year);
//		startManagingCursor(c);
		AnalysisAdapter aa = new AnalysisAdapter(this, R.layout.row_analysis, c, from, to);
		setListAdapter(aa);
		
		// if there isn't any data
		if (this.getListView().getCount() == 0) {
			// get rid of the chart view
			findViewById(R.id.view_analysis_chart).setVisibility(View.GONE);
		} else {
			// make sure chart view is in
			findViewById(R.id.view_analysis_chart).setVisibility(View.VISIBLE);
		}
	}

	/**
	 * When an analysis list item is clicked, filter the transaction view
	 * by the tag name and go to the transaction tab
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Cursor c = Buxoid.mDb.fetchAnalysis(id);
		startManagingCursor(c);
		if (c.getCount() > 0 && c.moveToFirst()) {
			Buxoid.mViewTag = c.getString(c.getColumnIndex(BuxoidDb.ANALYSIS_TAG));
		}
		
		Buxoid parent = (Buxoid) this.getParent();
		parent.getTabHost().setCurrentTabByTag("transactions");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuItem item;
		item = menu.add(0, UPDATE_ID, 1, R.string.menu_update);
		item.setIcon(android.R.drawable.ic_menu_set_as);
        
        // set settings menu item and icon
        item = menu.add(1, SETTINGS_ID, 2, R.string.menu_settings);
        item.setIcon(android.R.drawable.ic_menu_preferences);

		item = menu.add(0, HELP_ID, 3, R.string.menu_help);
		item.setIcon(android.R.drawable.ic_menu_help);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Intent i;
		switch(item.getItemId()) {
		case UPDATE_ID:
		    Buxoid.mUICallback = new Handler();
            Buxoid.mFinish = new Runnable () {
                public void run () {
                    fillData();
                }
            };
        	Buxoid.update(this);
        	return true;
        case SETTINGS_ID:
        	i = new Intent(this, EditSettings.class);
            startActivity(i);
            return true;
		case HELP_ID:
			i = new Intent(this, Help.class);
			i.putExtra("topic", "Expenses");
			this.startActivity(i);
			return true;
		}
		
		return super.onMenuItemSelected(featureId, item);
	}
	
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int month, int day) {
        	Buxoid.mYear = Math.min(year, Buxoid.mMaxYear);
        	Buxoid.mMonth = Math.min(month, Buxoid.mMaxMonth);
        	fillData();
        }
    };
}
